package com.taobao.mycamunda.controller;

import com.taobao.mycamunda.model.ActivityNodeVO;
import com.taobao.mycamunda.service.WorkflowTaskService;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.runtime.Execution;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.task.TaskQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RequestMapping("/workflow")
@RestController
public class WorkflowController {
    private final RepositoryService repositoryService;
    private final RuntimeService runtimeService;
    private final TaskService taskService;
    private final WorkflowTaskService workflowTaskService;

    private static Logger logger = LoggerFactory.getLogger(WorkflowController.class);

    public WorkflowController(RepositoryService repositoryService, RuntimeService runtimeService, TaskService taskService, WorkflowTaskService workflowTaskService) {
        this.repositoryService = repositoryService;
        this.runtimeService = runtimeService;
        this.taskService = taskService;
        this.workflowTaskService = workflowTaskService;
    }

    @PostMapping("deploy")
    public String deploy() {
        Deployment deployment = this.repositoryService.createDeployment()
                .addClasspathResource("diagram_1.bpmn")
                .name("测试流程")
                .deploy();
        logger.info("部署成功，部署ID：" + deployment.getId() + "," + deployment.getName());
        return "部署成功，部署ID：" + deployment.getId();
    }

    /**
     * 启动工作流实例时不带参数
     */
    @PostMapping("/startProcessInstance")
    public String startProcessInstance(@RequestBody String definitionId) {
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(definitionId);
        return "实例启动成功，实例ID：" + processInstance.getProcessInstanceId();
    }

    /**
     * 启动工作流时设置会签任务collection参数
     */
    @PostMapping("/startProcessInstance/v2")
    public String startProcessInstance2(@RequestBody String definitionId) {
        List<String> userList = new ArrayList<>();
        userList.add("joe");
        userList.add("book");

        Map<String, Object> variables = new HashMap<>();
        //variables.put("userList", userList);
        variables.put("manager","tony");

        ProcessInstance processInstance = runtimeService.startProcessInstanceById(definitionId, variables);
        return "实例启动成功，实例ID：" + processInstance.getProcessInstanceId();
    }

    @GetMapping("{processInstanceId}/tasks")
    public String getProcessInstanceTasks(@PathVariable String processInstanceId) {
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).active().list();
        tasks.forEach(x -> {
            System.out.println(x.getId() + "," + x.getName() + "," + x.getAssignee());
            logger.info(x.getId() + "," + x.getName() + "," + x.getAssignee());
        });

        return "流程实例共找到" + tasks.size() + "个任务";
    }

    @GetMapping("{processInstanceId}/nodes")
    public String getProcessInstanceNodes(@PathVariable String processInstanceId) {
        List<ActivityNodeVO> activityNodes = workflowTaskService.getActivityNodeList(processInstanceId);
        activityNodes.forEach(x -> {
            logger.info(x.getActivityId() + "," + x.getActivityName());
        });

        return "流程实例共找到" + activityNodes.size() + "个任务";
    }

    @GetMapping("/tasks/{assignee}")
    public void getTasks(@PathVariable String assignee) {
        TaskQuery taskQuery = taskService.createTaskQuery();
        List<Task> tasks = taskQuery.taskAssignee(assignee).list();
        tasks.forEach(x -> {
            logger.info(assignee + "待办任务:" + x.getId() + "," + x.getName());
        });
    }

    @PostMapping("/tasks/{taskId}")
    public String complete(@PathVariable String taskId) {
        taskService.complete(taskId);
        return taskId + "任务已完成";
    }

}
